@tool
extends MarginContainer

@onready var map_name_line_edit: LineEdit = $VBoxContainer/HBoxContainer/MapNameLineEdit
@onready var file_dialog: FileDialog = $FileDialog
@onready var save_button: Button = $VBoxContainer/GridContainer/SaveButton
@onready var load_button: Button = $VBoxContainer/GridContainer/LoadButton

var _plug:EditorPlugin
#var _face:EditorInterface
const _save_path = "res://Resources/MapData/";

func _ready() -> void:
	_plug = EditorPlugin.new()
	save_button.connect("pressed",_save_button_clicked)
	load_button.connect("pressed",_load_button_clicked)
	file_dialog.file_selected.connect(_load_map_data)
	
	pass
	
func  _save_button_clicked()->void:
	var sels = EditorInterface.get_selection().get_selected_nodes()
	if sels.size() != 1 :
		printerr("请直接选择TileMap")
		return
	if not sels[0] is TileMap:
		printerr("请选择TileMap节点")
		return
	if map_name_line_edit.text.is_empty() :
		printerr("请输入地图名称")
		return
	var map_data = {
		"map_name": map_name_line_edit.text,
		"data": []
	}
	var tile_map = sels[0] as TileMap
	var cells = tile_map.get_used_cells(0);
	for item in cells:
		var id = tile_map.get_cell_source_id(0,item)
		var coord = tile_map.get_cell_atlas_coords(0,item)
		var cell_data = {
			"x": item.x,
			"y": item.y,
			"source_id":id,
			"atlas_x":coord.x,
			"atlas_y": coord.y
		}
		map_data["data"].append(cell_data)
	var result = JSON.stringify(map_data,"\t")
	var file = FileAccess.open(_save_path + map_name_line_edit.text +'.json',FileAccess.WRITE)
	file.store_string(result)
	file.close()
	pass

func _load_button_clicked()->void:
	var sels = EditorInterface.get_selection().get_selected_nodes()
	if sels.size() != 1 :
		printerr("请直接选择TileMap")
		return
	if not sels[0] is TileMap:
		printerr("请选择TileMap")
		return
	var tile_map = sels[0] as TileMap
	file_dialog.show()
	pass
	
func _load_map_data(path:String)->void:
	if path.is_empty() : 
		return;
	var file = FileAccess.open(path,FileAccess.READ)
	var jsonstr = file.get_as_text()
	file.close()
	var json = JSON.parse_string(jsonstr)
	if json == null : 
		return
	map_name_line_edit.text = json["map_name"]
	var data = json["data"]
	if typeof(data) != TYPE_ARRAY :
		return
	var sels = EditorInterface.get_selection().get_selected_nodes()
	if not sels[0] is TileMap:
		printerr("当前未选中TileMap")
		return
	var tile_map = sels[0] as TileMap
	for item in data:
		tile_map.set_cell(0, Vector2i(item["x"],item["y"]),item["source_id"],Vector2i(item["atlas_x"],item["atlas_y"]))
		pass
	pass
